import datetime

from flask import Blueprint, redirect, make_response, request, render_template, abort, url_for, current_app
from webargs.flaskparser import use_kwargs

from app.chatgpt.login_web import AuthWeb
from app.chatgpt.login_web_ios import AuthWebIos
from app.config import GITHUB_AUTHORIZATION_URL, GITHUB_CLIENT_ID
from app.extensions import cache
from app.models import User
from app.schema import TokenFromArg
from app.utils import get_github_user, get_all_start

index_bp = Blueprint("index", __name__)


@index_bp.route('/')
def home():
    avatar_url = None
    user = User.get_by_token(request.cookies.get("access_token"))
    if user:
        avatar_url = user.user_info.get("avatar_url")
    return render_template('index.html', avatar_url=avatar_url)


@index_bp.route('/login')
def github_login():
    return redirect(f'{GITHUB_AUTHORIZATION_URL}?client_id={GITHUB_CLIENT_ID}&scope=user')


@index_bp.route('/oauth/github')
def callback():
    code = request.args.get('code')
    user_info, token_info = get_github_user(code)

    resp = make_response(redirect(url_for('index.home')))

    resp.set_cookie('access_token', token_info['access_token'], max_age=3600 * 24)
    User.save_data(user_info, token_info['access_token'])
    return resp


@index_bp.route('admin/user-list', methods=['GET'])
def get_user_list():
    return [{'name': i.user_info["name"], 'avatar_url': i.user_info["avatar_url"], 'email': i.user_info["email"]} for i in User.query.all()]


@index_bp.route('get-session-token', methods=['POST'])
@use_kwargs(TokenFromArg(), location="json")
def get_ssesion_token(**kwargs):
    # if current_app.debug:
    #     return AuthWeb().get_token_info(kwargs["username"], kwargs["password"])

    user = User.get_by_token(request.cookies.get("access_token"))
    if not user:
        abort(401, "请先登录，再使用该功能")
    key = "get-session-token:{}:{}".format(datetime.date.today(), user.user_id)
    r = cache.incr(key)

    user_id_list = get_all_start()

    if r > 3 and user.user_id not in user_id_list:
        abort(400, "每日仅限获取 3 次, 点击右上角项目，给个小星星，每日可获取 15 次")

    if r > 15:
        abort(400, "今日已达到获取上限")

    try:
        token_info = AuthWeb().get_token_info(kwargs["username"], kwargs["password"])
    except Exception as e:
        abort(400, str(e))

    return token_info


@index_bp.route('get-refresh-token', methods=['POST'])
@use_kwargs(TokenFromArg(), location="json")
def get_refresh_token(**kwargs):
    if current_app.debug:
        return AuthWebIos().get_token_info(kwargs["username"], kwargs["password"])

    user = User.get_by_token(request.cookies.get("access_token"))
    if not user:
        abort(401, "请先登录，再使用该功能")
    key = "get-refresh-token:{}:{}".format(datetime.date.today(), user.user_id)
    r = cache.incr(key)

    user_id_list = get_all_start()

    if r > 3 and user.user_id not in user_id_list:
        abort(400, "每日仅限获取 3 次, 点击右上角项目，给个小星星，每日可获取 10 次")

    if r > 10:
        abort(400, "今日已达到获取上限")

    try:
        token_info = AuthWebIos().get_token_info(kwargs["username"], kwargs["password"])
    except Exception as e:
        abort(400, str(e))

    return token_info
